<?php

namespace app\ports\controller\publics;

use think\Db;

/**
 * 实时计算 - 达标
 */
class Stands
{

	use \app\common\traits\ToolTrait;

	/**
	 * 对象实例
	 * @var object
	 */
	protected static $instance;

	/**
	 * 获取实例对象
	 * @return Binds|object
	 */
	public static function instance()
	{
		if (is_null(self::$instance)) {
			self::$instance = new static();
		}
		return self::$instance;
	}

	/**
	 * 处理
	 */
	public function handle($agid, $sn)
	{
		try {
			$tops = $this->topGroup($agid, $sn);
			if (!empty($tops)) {
				foreach ($tops as $vals) {
					$check = Teams::instance(date("Y-m-d"))->calc_able_personnel($vals);
					if ($check) {
						$direc = $this->_all_direct_level($vals);
						if ($direc) {
							$stands = [];
							foreach ($direc as $k => $v) {
								$teams = $this->_all_Lower_Level_teams_ids($v["id"]);
								array_push($teams, $v["id"]);
								$imp = implode(",", $teams);
								$stands_check_money = bcmul(\app\ports\constants\TeamsConstants::DEFAULT_STANDS_MONEY, '10000', 2);
								$teams_trans_money = $this->teams_trans_money($imp);
								if ((int)$teams_trans_money >= (int)$stands_check_money) {
									$childs = ["childs" => $v["id"], "money" => $teams_trans_money];
									array_push($stands, $childs);
								}
							}
							if (\app\ports\constants\TeamsConstants::DEFAULT_STANDS_NUMS <= count($stands)) {
								$this->_stands_upgrade($vals, $stands);
							}
						}
					}
				}
			}
		} catch (\Exception $e) {
			$this->logs("./portsLogs/upgrade", "bonus_calc_" . date("Y-m") . ".txt", [$e->getMessage()]);
		}
	}

	/**
	 * 达标晋级
	 * @param  $pid 达标计算代理ID
	 * @param  $times 计算时间
	 * @param  $data  交易数据
	 */
	protected function _stands_upgrade($pid, $data)
	{
		if (!empty($data)) {
			$con = count($data);
			$temps = Template::instance()->stands_calc($con);
			if ($temps) {
				$tmp = [];
				foreach ($temps as $val) {
					$i = 0;
					foreach ($data as  $v) {
						if ($val["money"] <= $v["money"]) $i++;
					}
					$tmp[$val["code"]] = $i;
				}
				if ($tmp) {
					// 	// 匹配达标模板
					foreach ($tmp as $k => $v) {
						$check = Template::instance()->_check_use_stands($k, $v);
						if ($check) {
							$times = date("Y-m");
							$this->_store_upgrade_cords($k, $pid, $times, $data);
						}
					}
				}
			}
		}
	}

	/**
	 * 存储晋级记录
	 * @param  $id  等级ID
	 * @param  $pid 达标计算代理ID
	 * @param  $times 计算时间
	 * @param  $data  交易数据
	 */
	public function _store_upgrade_cords($lev_code, $pid, $times, $data)
	{
		if (!empty($lev_code) && !empty($pid) && !empty($times) && !empty($data)) {
			$times = strtotime($times);
			$option = [
				"agid"		=> $pid,
				"lev_code"	=> $lev_code,
				"times"		=> $times,
				"isReals"	=> 1
			];
			$check = Db::name("bonus_upgrade")->where($option)->count();
			if (!$check) {
				$option["stands"] = json_encode($data);
				$option["createTime"] = time();
				$res =  Db::name("bonus_upgrade")->insert($option);
				if ($res) {
					$obj = new Rule();
					$obj->store_xu($option);
				}
			}
		}
	}

	/**
	 * 获取团队交易
	 */
	public function teams_trans_money($team_child_ids)
	{
		$sum = "0.00";
		if (!empty($team_child_ids)) {
			$times = strtotime(date("Y-m"),  time());
			// $table = "fd_bonus_calc_trans_days_" . date("Y", $times);
			$table = "fd_bonus_calc_trans_" . date("Y", $times);
			$isExist = Db::query("SHOW TABLES like '" . $table . "'");
			if ($isExist) {
				$sum  = Db::table($table)
					->where("agid in (" . $team_child_ids . ") and times = " . $times)
					->sum("transAmt");
			}
			// ->where("agid in (" . $team_child_ids . ") and ( times >= " . strtotime(date("Y-m-01", time())) . " and times < " . $times . ")")
		}
		return $sum;
	}

	/**
	 * 所有直属下级
	 * @return array|bool
	 */
	public function _all_direct_level($pid)
	{
		if (!empty($pid)) {
			$where = "pid = {$pid} and ptype = 2";
			$query = Db::name("user")
				->field("id")
				->where($where)
				->select();
			if ($query) return $query;
		}
		return false;
	}

	/**
	 * 所有上级
	 * @return array
	 */
	public function topGroup($agid, $sn)
	{
		// dump($agid);
		$data = [];
		$frams = \app\common\func\Tools::getUserData($sn);
		if ($frams) {
			foreach ($frams as $key => $vals) {
				if ($vals["id"] != $agid && $vals["utype"] == 2) {
					// dump($vals);
					array_push($data, $vals["id"]);
				}
			}
		}
		return $data;
	}


	/**
	 * 所有下级
	 * @return array
	 */
	public function _all_Lower_Level_teams_ids($pid, array &$array = [])
	{
		try {
			if (!empty($pid)) {
				$childLists = $this->framsChilds($pid);
				if ($childLists) {
					foreach ($childLists as $vals) {
						if ($vals["ptype"] == 2) {
							$array[] = $vals["id"];
						}
						$this->_all_Lower_Level_teams_ids($vals["id"], $array);
					}
				}
			}
		} finally {
			return $array;
		}
	}

	/**
	 * 管理架构 - 获取下级
	 * @param string $uniques
	 * @return array
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\DbException
	 * @throws \think\db\exception\ModelNotFoundException
	 */
	public function framsChilds($pid)
	{
		$data = []; //初始化返回参数
		try {
			if ($pid) {
				// 获取下级业务员
				$where = "pid = {$pid} and ptype = 2";
				$query = Db::name("user")
					->field("id,pid,ptype")
					->where($where)
					->select();
				if ($query) {
					$data = $query;
				}
			}
		} finally {
			return $data;
		}
	}
}

/**
 * 新规则 - 虚
 */
class Rule
{
	public function store_xu($option = [])
	{
		$times = "2023-10-01";
		$current = date("Y-m-d");
		if (strtotime($times) > strtotime($current)) exit();
		if (!empty($option)) {
			$ret = $this->insert_isplay_days($option["agid"]);
			if ($ret) {
				foreach ($ret as $vals) {
					$check = $this->_check_stores($vals["days"]);
					if ($check) {
						$where = [];
						$option["agid"] = $vals["uid"];
						$option["isReals"] = 2;
						$where = ["agid" => $option["agid"], "lev_code"	=> $option["lev_code"], "times"	=> $option["times"], "isReals"	=> $option["isReals"]];
						$check_store = Db::name("bonus_upgrade")
							->where($where)
							->count();
						if (!$check_store) {
							$option["state"] = 2;
							$option["createTime"] = strtotime("+" . $vals["days"] . "day", time());
							Db::name("bonus_upgrade")->insert($option);
						}
					}
				}
			}
		}
	}

	/**
	 * 是否达标存储 
	 * @return boolean
	 */
	protected function _check_stores($days)
	{
		$check = false;
		if ($days) {
			$storeDate = strtotime("+" . $days . "day", strtotime(date("Y-m-d")));
			$lastDayOfMonth = strtotime(date('Y-m-t'));
			if ($lastDayOfMonth >= $storeDate) return true;
		}
		return $check;
	}

	/**
	 * @return array|boolean
	 */
	protected function insert_isplay_days($id)
	{
		if ($id) {
			$data = [];
			// 1-3  7-10 7-10 12-15 随机
			// $arr = [0 => rand(1, 3), 1 => rand(7, 10), 2 => rand(7, 10), 3 => rand(12, 15)];
			$arr = [0 => 1 , 1 => 2 , 2 => 3, 3 => 4];
			$clone_res = \app\common\func\Tools::copyUsers($id);
			if ($clone_res) {
				for ($i = 0; $i < count($clone_res); $i++) {
					$temp = [];
					$temp["days"] = $arr[$i];
					$temp["uid"]  = $clone_res[$i];
					array_push($data, $temp);
				}
			}
			return $data;
		}
		return false;
	}
}
